# -*- coding: utf-8 -*-

import logging
import subprocess
import os
import json


def get_data(filename):
    command = [
        "ffprobe.exe",
        "-loglevel", "quiet",
        "-print_format", "json",
        "-show_format",
        "-show_streams",
        "-i", filename
    ]
    result = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    out = result.stdout.read()
    data = json.loads(out.decode("utf-8"))
    return data


def gen_singlepicvideo(output, picname, length, crf=22):
    command = [
        "ffmpeg",
        "-loop", "1",
        "-r", "1",
        "-t", str(int(length)),
        "-f", "image2",
        "-i", picname,
        "-c:v", "libx264",
        "-crf", str(crf),
        "-y", output
    ]
    result = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    result.stdout.read()
    if os.path.exists(output):
        return True
    else:
        return False


def gen_mp4(video_file, music_file, output):
    command = [
        "ffmpeg",
        "-i", video_file,
        "-i", music_file,
        "-c:v", "copy",
        "-c:a", "copy",
        "-y", output
    ]
    result = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    result.stdout.read()
    if os.path.exists(output):
        return True
    else:
        return False


def gen_onepicvideo(pic_file, music_file, output):
    logging.info(
        "生成一图流视频(pic: \"%s\", music: \"%s\", output: \"%s\")"
        % (pic_file, music_file, output))
    length = float(get_data(music_file)["streams"][0]["duration"])
    logging.debug("视频长度: %ss" % length)
    if gen_singlepicvideo("tmp.mp4", pic_file, length):
        logging.info("生成图片视频成功")
    else:
        logging.info("生成图片视频失败")
        return False
    if gen_mp4("tmp.mp4", music_file, output):
        logging.info("合并视频成功")
    else:
        logging.info("合并视频失败")
        return False
    try:
        os.remove("tmp.mp4")
    except FileNotFoundError:
        pass
    return True


if __name__ == "__main__":
    gen_onepicvideo(
        ".\\res\\INPUT.jpg",
        ".\\res\\INPUT.mp3",
        ".\\res\\OUTOUT.mp4"
    )
